package org.jeecg.modules.util;

import com.alibaba.fastjson.JSONObject;
import com.xkcoding.http.support.Http;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

@Slf4j
public class HttpUtils {
    public static String sendPostJson(JSONObject json, String URL) {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(URL);
        post.setHeader("Content-Type", "application/json");
        post.addHeader("Authorization", "Basic YWRtaW46");
        String result = null;
        InputStream inStream = null;
        try {
            StringEntity str = new StringEntity(json.toString(), "utf-8");
            str.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            post.setEntity(str);
            // 发送请求
            CloseableHttpResponse httpResponse = client.execute(post);
            // 获取响应输入流
            inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null)
                strber.append(line + "\n");
            inStream.close();
            result = strber.toString();
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
                log.info("请求服务器成功");
            } else {
                log.info("请求服务端失败");
            }
        } catch (Exception e) {
            System.out.println("发送POST请求出现异常！" + e);
            e.printStackTrace();
        } finally {
            // 使用finally块来关闭输入流
            try {
                if (inStream != null) {
                    inStream.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    public static void sendPostJsonWriteRes(JSONObject json, String URL, HttpServletResponse res) {
        System.out.println("请求服务器");
        System.out.println("json:"+json.toJSONString());
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(URL);
        post.setHeader("Content-Type", "application/json");
        InputStream inStream = null;
        ServletOutputStream outputStream = null;
        FileOutputStream fos = null;
        try {
            StringEntity str = new StringEntity(json.toString(), "utf-8");
            str.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            post.setEntity(str);
            // 发送请求
            System.out.println("发送请求");
            CloseableHttpResponse httpResponse = client.execute(post);
            // 获取响应输入流
            inStream = httpResponse.getEntity().getContent();
            outputStream = res.getOutputStream();
            fos = new FileOutputStream(new File("/root/ss.jpg"));
            byte[] buffer = new byte[1024];
            int len = inStream.read(buffer);
            while (len != -1) {
                outputStream.write(buffer, 0, len);
                fos.write(buffer,0,len);
                len = inStream.read(buffer);
            }
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
                System.out.println("请求服务器成功");
            } else {
                System.out.println("请求服务端失败");
            }
        } catch (Exception e) {
            System.out.println("发送POST请求出现异常！" + e);
            e.printStackTrace();
        } finally {
            // 使用finally块来关闭输入流
            try {
                if (inStream != null) {
                    inStream.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url：发送请求的URL
     * @return String[result]：所代表远程资源的响应结果
     */
    public static String sendGet(String url) {
        System.out.println("LukasLi:"+url);
        String result = "";
        BufferedReader in = null;
        try {
//            String urlNameString = url;
            URL realUrl = new URL(url);

            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();

            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            // 建立实际的连接
            connection.connect();

            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();

            // 遍历所有的响应头字段
            System.out.println("LukasLi:map <--");
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            System.out.println("LukasLi:map -->");
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        } finally {
            // 使用finally块来关闭输入流
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        System.out.println("LukasLi"+result);
        return result;
    }
}
